import requests
'''
爬取酷我搜索结果
'''

# url = "http://www.kuwo.cn/api/www/search/searchMusicBykeyWord?key=%E6%9D%8E%E8%8D%A3%E6%B5%A9&pn=1&rn=30&httpsStatus=1&reqId=6511ce60-c146-11ec-974a-e11c82c3f6c5"
url = "http://www.kuwo.cn/api/www/search/searchMusicBykeyWord"
heards = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.88 Safari/537.36"
    ,"Referer": "http://www.kuwo.cn/search/list?key=%E6%9D%8E%E8%8D%A3%E6%B5%A9",
    "Cookie": "Hm_lvt_cdb524f42f0ce19b169a8071123a4797=1650526536; _ga=GA1.2.1741002322.1650526536; _gid=GA1.2.418583138.1650526536; Hm_lpvt_cdb524f42f0ce19b169a8071123a4797=1650526809; kw_token=I2QQB81OLQ"
    ,"csrf":"I2QQB81OLQ"
}
#http://www.kuwo.cn/api/v1/www/music/playUrl?mid=156483846&type=music&httpsStatus=1&reqId=f4464051-c14d-11ec-9f90-c38172b190fb
params = {
    "key":"踏山河",
    "pn":"1",
    "rn":"30",
    "httpsStatus":"1"
}
params['key'] = "tfboys"
resp = requests.get(url=url, headers=heards, params=params)
data = resp.json()
# print(resp.text)
import prettytable as pt
table = pt.PrettyTable()
table.field_names = ['序号', '歌名', '歌手', '专辑']
data_list = data['data']['list']

i = 1
for d in data_list:
    artist = d['artist']
    name = d['name']
    pic_url = d['pic']
    album = d['album']
    rid = d['rid']
    play_url = f'http://www.kuwo.cn/api/v1/www/music/playUrl?mid={rid}&type=music&httpsStatus=1&reqId=b7fda6f1-c149-11ec-a4f6-1f6ad69b2c69'

    table.add_row([rid, name, artist, album])
    resp1 = requests.get(play_url)
    music_data = resp1.json()
    if music_data['code'] == 200:
        music_url = music_data['data']['url']
        print(music_url)
        resp2 = requests.get(music_url)
        # with open('./文件/'+name+".mp3", mode='wb') as f:
        #     f.write(resp2.content)
    if i == 1:
        break


print(table)